import { showLoading } from '@app-nextmesh-env/nextmesh/components';
import { ITreeNode } from '@app-nextmesh-env/nextmesh/components/types';
import { documentV2 } from '@app-nextmesh-env/nextmesh/domain';
import { nmAppErrorLog } from '@app-nextmesh/common/utils';
import { i18n } from '@app-nextmesh/common/utils';
import { cloneDeep } from 'lodash';
import AlertDialog from '../AlertDialog';
import { IProps } from './typs';

interface IItemProps extends IProps {
  data: ITreeNode;
  name: string; // derived/plots
  formIndex: number;
}
export default function VisualizationItemAlertDialog({
  data,
  name,
  formIndex,
  onUpdate,
  onClose,
}: IItemProps) {
  const doDelete = async () => {
    let hide: () => void;
    const formData = cloneDeep(data.formData);
    const items = formData[name];
    if (items) {
      items.splice(formIndex, 1);
      hide = showLoading();
      try {
        const rspData = await documentV2.updatePostprocess(formData);
        onUpdate(rspData);
      } catch (error) {
        nmAppErrorLog('VisualizationItemDelete', error);
      } finally {
        hide();
        onClose();
      }
    }
  };
  return (
    <AlertDialog
      alert={i18n.t('confirmDelete', { name: i18n.t(name) })}
      primaryTitle={i18n.t('deleteTip')}
      onPrimaryClick={doDelete}
      onSecondaryClick={onClose}
    />
  );
}
